<?php

namespace App\Http\Controllers\Api;

use App\Http\Resources\CommentResource;
use App\Http\Resources\StickyTopicResource;
use App\Http\Resources\SwiperResource;
use App\Http\Resources\TopicResource;
use App\Models\StickyTopic;
use App\Models\Swiper;
use App\Models\Tag;
use App\Models\TopicTag;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Repositories\TopicRepository;
use App\Repositories\CommentRepository;
use App\Transformers\ForumTransformer;
use App\Transformers\TopicTransformer;
use Illuminate\Support\Arr;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use App\Models\Topic;
use App\Models\Forum;
use App\Http\Requests\TopicRequest;
use Illuminate\Support\Facades\Auth;

class TopicController extends Controller
{
    protected $topic;
    
    protected $comment;
    
    public function __construct(TopicRepository $topic, CommentRepository $comment)
    {
        $this->topic = $topic;
        $this->comment = $comment;
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $with = ['user', 'forum', 'mainFloor', 'mainFloor.detail', 'mainFloor.detail.attachments'];
        $query = Topic::query()->with($with);
        $forumKey = $request->fid;
        $topicKey = $request->topic_key;
        $userKey = $request->user_key;
        $hasSetOrderBy = false;

        if ($forumKey) {
            $query->whereHas("forum", function ($query) use ($forumKey) {
                $query->where("id", $forumKey);
            })->orderBy("last_comment_time", "desc");
            $hasSetOrderBy = true;
        }

        if ($userKey) {
            $query->whereHas("user", function ($query) use ($userKey) {
                $query->where("key", $userKey);
            })->orderBy('id', 'desc');
            $hasSetOrderBy = true;
        }

        if ($topicKey) {
            $query->where('key', $topicKey);
        }

        if (!$hasSetOrderBy) {
            $query->orderBy('id', 'desc');
        }

        $collection = $query->paginate($request->get('per_page', 10));
        $resource = TopicResource::collection($collection);

        return api(RET_OK, MSG_OK, $resource);

    }

    public function my(Request $request)
    {
        $with = ['user', 'forum', 'mainFloor', 'mainFloor.detail', 'mainFloor.detail.attachments'];
        $user = auth_user();
        $collection = Topic::query()->with($with)->where('uid', $user->id)->paginate();
        $resource = TopicResource::collection($collection);
        return api(RET_OK, MSG_OK, $resource);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(TopicRequest $request)
    {
        $user = Auth::user();
        $result = $this->topic->create($request, $user);
        if ($result['ret'] !== 0)
        {
            return $result;
        }
        $request->query->add([
            'forum_key' => $result['data']['forum']->key,
            'topic_key' => $result['data']['topic']->key,
            'detail_excerpt' => 1,
        ]);
        return $this->index($request);
    }

    /**
     * 话题详情
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $request = request();
        $result = (new TopicRepository())->topicDetailData($id, $request->page);
        $comments = $result['comments'];
        $topic = $result['topic'];
        $resource = CommentResource::collection($comments);
        if ($request->page <= 1 && $comments->isNotEmpty()) {
            $topic->increment('view_count');
            $additional = [
                'topic' => new TopicResource($topic),
            ];
            if ($result['can_see_topic_hide']) {
                $reportFields = [
                    'action_time', 'action_province' , 'action_city', 'action_district',
                    'action_location',  'longitude', 'latitude'
                ];
                $additional['report'] = $topic->only($reportFields);
            }
            $resource->additional($additional);

        }

        return api(RET_OK, MSG_OK, $resource);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(TopicRequest $request, $id)
    {
        $data = $request->all();
        $result = $this->topic->update($data, $id);
        return $result;
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function sticky(Request $request)
    {
        $query = StickyTopic::query()->with(['topic', 'topic.mainFloor', 'topic.mainFloor.detail'])
            ->orderBy('display_order', 'desc');

        $position = $request->position;
        if ($position == StickyTopic::POSITION_INDEX) {
            $query->positionIndex();
        } elseif ($position == StickyTopic::POSITION_FORUM) {
            $query->positionForum();
        }

        if ($request->fid) {
            $fid = $request->fid;
            $query->whereHas('topic', function ($query) use ($fid) {
                $query->where('fid', $fid);
            });
        }

        $collection = $query->get();

        $resource = StickyTopicResource::collection($collection);

        return api(RET_OK, MSG_OK, $resource);

    }

    public function config(Request $request)
    {
        $forums = Forum::all(['name', 'id']);
        $topicTypes = [];
        foreach (Topic::$types as $type => $name) {
            $topicTypes[] = [
                'id' => $type,
                'text' => $name,
            ];
        }
        $provinceCityDistrict = (new TopicRepository())->provinceCityDistrict($request);

        $tags = Tag::query()->get(['id', 'name']);

        $out = compact('topicTypes', 'forums', 'tags', 'provinceCityDistrict');

        return api(RET_OK, MSG_OK, $out);
    }
}
